const express = require("express");
const mysql = require("mysql2");

const options = {
  host: "localhost",
  port: 3306,
  user: "root",
  password: "123456789",
  database: "oppo",
};

// 根据数据库配置创建数据库连接
const connection = mysql.createConnection(options);
connection.connect(); // 连接到数据库服务器

const state = require("../state.js");
console.log(state.login);

const router = express.Router();


//会话
let checkLogin = (req, resp, next) => {
  if (req.session.username) {
    next();
    return;
  }
  // 返回到教师登录页面
  resp.render("user/sign-in", { message: "请先登录" });
};

router.all("/good/remove/:goodid", checkLogin);
router.all("/good/list", checkLogin);
router.all("/good/jiesuan", checkLogin);



router.get("/good/list", (req, resp) => {
  let sql = `SELECT * FROM t_goods `;

  let handler = function (error, results, fields) {
    if (error) {
      console.log("查询失败");
      throw error;
    }
    // '/views/good/list.njk'
    let view = "good/list";
    let data = {
      goods: results,
    };
    resp.render(view, data);
  };

  // 从数据库中查询教师数据
  connection.query(sql, handler);
});

router.get("/good/remove/:goodid", (req, resp) => {
  // 获取路由参数
  let goodid = req.params.goodid;
  let sql = "DELETE FROM t_goods WHERE goodid = " + goodid;
  let handler = (error, results, fields) => {
    if (error) {
      console.log("删除失败");
      throw error;
    }
    console.log(results);
    // 删除成后重新返回到列表
    resp.redirect("/good/list");
  };
  connection.query(sql, handler);
});

router.get("/good/add", (req, resp) => {
  resp.render("good/add");
});

router.post("/good/add", (req, resp) => {
  let goodname = req.body.goodname;
  let price = req.body.price;

  let sql = `insert into t_goods (goodname,price) values ('${goodname}','${price}')`;

  let handler = function (error, results, fields) {
    if (error) {
      console.log("添加失败");
      throw error;
    }
    resp.redirect("/good/list");
  };
  connection.query(sql, handler);
});

router.get("/good/add2", (req, resp) => {
  resp.render("good/add2");
});

router.post("/good/add2", (req, resp) => {
  let goodname = req.body.goodname;
  let price = req.body.price;

  let sql = `insert into t_goods (goodname,price) values ('${goodname}','${price}')`;

  let handler = function (error, results, fields) {
    if (error) {
      console.log("添加失败");
      throw error;
    }
    resp.redirect("/good/list");
  };
  connection.query(sql, handler);
});

router.get("/good/jiesuan", (req, resp) => {
    resp.render("good/jiesuan");
  });

module.exports = router;
